from odoo import models, fields, api, _
from odoo.exceptions import UserError
import datetime


class SBCreditNoteWizard(models.TransientModel):
    _name = 'sb.credit.note.wizard'
    _description = 'Credit Note Wizard'

    sb_checking_id = fields.Many2one('sb.account.checking', string='Account Checking', required=True)
    amount = fields.Monetary(string='Amount', required=True)
    reason = fields.Text(string='Reason', required=True)
    currency_id = fields.Many2one('res.currency', string='Currency', related='sb_checking_id.currency_id', readonly=True)
    journal_id = fields.Many2one(
        'account.journal', string='Journal', required=True,
        domain=[('type', '=', 'sale')],  # 出口退款使用 sale 类型
        default=lambda self: self.env['account.journal'].search([('type', '=', 'sale')], limit=1)
    )
    account_id = fields.Many2one(
        'account.account',
        string='Income Account',
        required=True,
        domain=[('deprecated', '=', False)],
        default=lambda self: self.sb_checking_id.revenue_account_id
    )

    def action_confirm(self):
        self.ensure_one()
        checking = self.sb_checking_id
        if not checking.invoice_ids:
            raise UserError(_('无发票可关联。'))

        # 默认关联第一张发票的客户、公司
        partner = checking.customer
        invoice = checking.invoice_ids[0]
        company = invoice.company_id

        # 创建退款单
        refund = self.env['account.move'].create({
            'move_type': 'out_refund',
            'partner_id': partner.id,
            'invoice_origin': checking.name,
            'invoice_date': datetime.date.today(),
            'currency_id': checking.currency_id.id,
            'journal_id': self.journal_id.id,
            'invoice_line_ids': [
                (0, 0, {
                    'name': self.reason or '质量问题扣款',
                    'quantity': 1,
                    'price_unit': self.amount,
                    'account_id': self.account_id.id,
                })
            ],
        })

        # 将创建的 Credit Note 关联回对账单
        checking.write({'credit_note_ids': [(4, refund.id)]})

        return {
            'type': 'ir.actions.act_window_close'
        }
